<template>
  <!-- 导航栏 -->
    <van-nav-bar
      title="确认订单"
      left-text="返回"
      left-arrow
      fixed
      placeholder
      z-index="1000"
      @click-left="back"
    />


    <!-- 收货地址 -->
    <van-contact-card v-if="address" type="edit" :name="`${address.name} ${address.region_text}`" :tel="address.tel" @click="OnAddelect" />
    <van-contact-card v-else type="add" @click="OnAddelected" />

    <!-- 商品卡片 -->
    <van-card
        v-for="(item,key) in list" :key="key"
        :num="item.nums"
        :thumb="item.product.thumb_text"
        @click-thumb="toProductInfo(item.proid)"
    >
        <template #title>
            <div class="title">{{item.product.name}}</div>
        </template>

        <!-- 商品规格 -->
        <template #desc v-if="item.attrs">
            <div class="TagGroup">
                <van-tag v-for="(items, index) in item.attrs" :key="index" class="tag" type="primary">{{ items.value }}</van-tag>    
            </div>
        </template>
        <template #desc v-else>
            <div class="TagGroup">
                <van-tag class="tag" type="primary">无商品规格</van-tag>    
            </div>
        </template>
        
        <template #tags>
            <div class="price">单价：{{item.price}}</div>
        </template>
        <template #price>
            <div class="price">合计：{{ item.total }}</div>
        </template>
    </van-card>

    <!-- 选择支付 -->
    <van-cell is-link title="支付方式" @click="PayShow=true" :value="PayAction.text"></van-cell>

    <van-coupon-cell
        :coupons="CouponsList"
        :chosen-coupon="ChosenCoupon"
        @click="CouponShow = true"
        
    />

    <!-- 订单备注 -->
    <van-field
        v-model="remark"
        rows="2"
        autosize
        label="订单备注"
        type="textarea"
        maxlength="50"
        placeholder="请输入备注内容"
        show-word-limit
    />

    <!-- 优惠券选择器 -->
    <van-popup
        v-model:show="CouponShow"
        position="bottom"
        style="height: 90%; padding-top: 4px;"
    >
        <van-coupon-list
            :coupons="CouponsList"
            :chosen-coupon="ChosenCoupon"
            :exchange-button-disabled="true"
            :show-exchange-bar="false"
            @change="Couponselect"
        />
    </van-popup>

    <!-- 支付选择弹出框 -->
    <van-popup v-model:show="PayShow" position="bottom">
        <van-picker
            title="选择支付"
            :columns="PayList"
            @cancel="PayShow = false"
            @confirm="PayConfirm"
            />
            <!-- @confirm="PayConfirm" -->
    </van-popup>

  <!-- 提交动作栏 -->
  <van-submit-bar :price="total" text-align="left" @submit="submit" button-text="确认支付">
  </van-submit-bar>
</template>

<script setup>

    const {proxy} = getCurrentInstance()

    let cartid = proxy.$route.query.cartid ? proxy.$route.query.cartid : '0'
    // let address = proxy.$address 
    let business = proxy.$business
    let address = ref(null)//空地址
    let list = ref([])

    //支付方式
    let PayShow = ref(false)
    let PayAction = ref({text:'余额支付', value: 'money'})
    let PayList = ref([
        {text:'余额支付', value:'money'},
        {text: '微信支付', value: 'wx'},
        {text: '支付宝支付', value: 'zfb'}
    ])

    //订单备注
    let remark = ref('')

    //优惠卷
    let CouponsList = ref([])
    let CouponShow = ref(false)
    let ChosenCoupon = ref(-1)


    onMounted(() => {
        CartInfo()
        CouponsInfo()
        AddressInfo()
    })

    // 计算总价 computed 计算属性 vue自带
    const total = computed(() => {
        //给total初始化值
        var total = 0

        //根据勾选的元素来计算价格 map循环遍历
        list.value.map((item) => {
            total += parseFloat(item.total)
        })

        //使用优惠卷
        if(ChosenCoupon.value != -1)
        {
            // 计算优惠卷 选择优惠卷  拿到优惠卷的折扣比例
            var cate = CouponsList.value[ChosenCoupon.value].rate
            // console.log(CouponsList.value[ChosenCoupon.value])

            // 计算总价  总价 * 折扣比例
            total = total * cate
        }
        return parseFloat(total*100)
    })

     //收获地址
     const AddressInfo = async() => 
    {
        //先从缓存中获取地址，如果有就赋值，没有就通过接口去拿
        if(proxy.$address.value)
        {
            // console.log(123)
            // console.log(proxy.$address.value)
            address.value = proxy.$address.value
            // console.log(address.value)
        }else
        {
            var result = await proxy.$POST({
                url:'/address/selectd', 
                params:{busid:business.value.id}
            })

            if(result.code==0) return false

            address.value = result.data
            
        }
    }

    //购物车信息
    const CartInfo = async () => {
        var params = {
        busid:proxy.$business.value.id,
        cartid
        }
        var result = await proxy.$POST({
            url:'/cart/index',
            params
        })
        // console.log(result)
        if(!result) return false

        if(result.code == 0)
        {
            proxy.$fail(result.msg)
            return false
        }

        //赋值购物车列表  循环
        result.data.map(item => item.attrs = JSON.parse(item.attrs))

        list.value = result.data
        // console.log(list.value)

    }

    //优惠卷
    const CouponsInfo = async () => {
        var result = await proxy.$POST({
            url:'/business/coupon',
            params:{busid:business.value.id}
        })

        // console.log(result)
        if(result.code && result.data.length > 0)
        {
            //给个空数组
            var coupon = []

            //for...of 循环在JavaScript中是用来遍历可迭代对象的一种结构
            for(var item of result.data)
            {
                //追加数值进去
                coupon.push({
                    id:item.id,
                    name:item.coupon.title,
                    rate:item.coupon.rate,
                    condition:item.coupon.status_text,
                    startAt:item.coupon.createtime,
                    endAt:item.coupon.endtime,
                    valueDesc:`${item.coupon.rate * 100}`,
                    unitDesc:'折'
                })
            }

            CouponsList.value = coupon

        }
        
    }

    //支付方式
    const PayConfirm = async({selectedOptions}) => {
        PayShow.value = false
        PayAction.value = selectedOptions[0]
        
    }


    //选择优惠卷
    const Couponselect = (index) => {
        CouponShow.value = false
        ChosenCoupon.value = index

        //使用优惠卷
        if(index != -1)
        {
            //拿到选择优惠卷后的总价格
            var TotalPice = total.value / 100 
            // console.log(total.value)

            // 计算优惠卷 选择优惠卷  拿到优惠卷的折扣比例
            var cate = CouponsList.value[index].rate

            //计算总价
            var Total = TotalPice * cate

            //用优惠卷之后的总价减去总价
            var CouponPice = TotalPice - Total

            // console.log(CouponPice)
            //parseFloat将一个字符串转换为浮点数 toFixed保留两位小数
            CouponPice = parseFloat(CouponPice * 100).toFixed(2)
            //拿到值渲染到页面
            CouponsList.value[index].value = CouponPice
            // console.log(CouponPice)

        }
    }

    //跳转收获地址的页面
    const OnAddelect = () => {
        //传个elsect这个参数是为了判断是从地址列表过来的还是会员收货地址过来的
        proxy.$router.push({path:'/address', query:{action:'elsect'}})
    }

    // 跳转添加收获地址的页面
    const OnAddelected = () => {
        proxy.$router.push('/address/add')
    }


   
    const ProductInfo = () => proxy.$router.push('/product/info')

    //返回上一页
    const back = () => proxy.$router.go(-1)

    //提交订单
    const submit = async() => {

        // console.log(business.value)
        // return false

        var params = {
            busid:business.value.id,
            address:address.value.id,
            remark:remark.value,
            pay:PayAction.value.value,
            cartid:cartid
        }

        if(ChosenCoupon.value != -1)
        {
            params.couponid = CouponsList.value[ChosenCoupon.value].id
        }

        var result = await proxy.$POST({
            url:'/order/add',
            params
        })

        if(result.code == 0)
        {
            proxy.$fail(result.msg)
            return false
        }

        if(params.pay == 'money')
        {
            proxy.$success({
                message: result.msg,
                //后台传了个orderid
                onClose: () => proxy.$router.push({path:result.url, query:{orderid: result.data.orderid}})
            })
        }

        // proxy.$success({
        //     message:result.msg,
        //     onClose:() => {
        //         proxy.$router.push('/order/info')
        //     }
        // })
        // console.log(Check.value)
    }
</script>

<style scoped>
  :deep(.cart) {
    display: flex;
    width: 100%;
  }
  ::v-deep .van-swipe-cell {
    width: 100%;
  }
  .delete-button {
    height: 100%;
  }


  .van-card{
    background-color:#fff;
  }

  .title{
    font-size:16px;
    font-weight: bold;
    margin-bottom:5px;
  }

  .TagGroup{
    margin-bottom:5px;
  }

  .tag{
    margin-right:5px;
  }

  .price{
    font-size:14px;
    font-weight: bold;
  }
</style>